package cn.lzd.ui.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import cn.lzd.ui.R;

/**
 * @author lzd
 * 省略文本TextView
 * Warning：仅支持单行，末尾省略
 * 功能：可以设置在末尾省略文本时，保留几个字符，如字符串：【我是一个字符串】，需要保留为【我是一个...串】
 *      则可以通过设置{@link EllipsizeTextView#saveLength} 值为2，来实现此功能
 */
public class EllipsizeTextView extends androidx.appcompat.widget.AppCompatTextView {
    public EllipsizeTextView(@NonNull Context context) {
        this(context, null);
    }

    public EllipsizeTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EllipsizeTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private Paint mPaint;
    /** 省略文字时要保留最后的几个字符 */
    private int saveLength;

    private void init(Context context, AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.EllipsizeTextView);
            saveLength = typedArray.getInteger(R.styleable.EllipsizeTextView_uibase_saveWordLength, 0);
            typedArray.recycle();
        }

        setSingleLine(true);
        setEllipsize(TextUtils.TruncateAt.END);
        mPaint = getPaint();
        mPaint.setAntiAlias(true);
    }

    public void setSaveLength(int saveLength) {
        this.saveLength = saveLength;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (!drawText(canvas)) {
            super.onDraw(canvas);
        }
    }

    /**
     * 绘制文本，如果当前行没有出现省略字符 或 saveLength 小于等于0，则交由父类绘制
     * @return 返回 false 则需由父类绘制
     */
    private boolean drawText(Canvas canvas) {
        String text = getText().toString();
        int mViewWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
        float textWidth = mPaint.measureText(text);
        if (textWidth > mViewWidth && saveLength > 0) {
            String ellipsizeText = "..." + text.substring(Math.max(0, text.length() - saveLength));
            float ellipsisWidth = mPaint.measureText(ellipsizeText);
            float authenticTextWidth = mViewWidth - ellipsisWidth;
            for (int i = 0; i < text.length() - saveLength; i++) {
                if (mPaint.measureText(text.substring(0, i + 1)) > authenticTextWidth) {
                    text = text.substring(0, i) + ellipsizeText;
                    break;
                }
            }
            float lineY = getMeasuredHeight() - getPaddingBottom() - 13;
            float lineX = getPaddingLeft();
            canvas.drawText(text, lineX, lineY, mPaint);
            return true;
        }
        return false;
    }
}
